## MPS得truncation error的代码，有点长，单独放着
def get_truncated_weight(propstring):  ## for any energy levels
    import numpy
    from copy import deepcopy

    def load_truncated_weight_for_dset_general_level(DataSet):
        ## 得到truncated_weight的核心:
        def load_truncated_weight_for_dset(filename):
            #根据filename在h5文件中强行找到这个DataSet对应的truncated_weight
            ar = pyalps.hdf5.archive(filename)
            sweeps = ar.list_children('/spectrum/iteration')
            sweeps = [int(s) for s in sweeps]
            max_sweep = max(sweeps)
            truncated_weight_list = ar['/spectrum/iteration/' + str(max_sweep)
                                       + '/results/TruncatedWeight/mean/value']
            truncated_weight = max(truncated_weight_list)
            return truncated_weight

        num_levels = len(DataSet.y)
        truncated_weights = []
        if num_levels > 1:
            for i in range(num_levels):
                filename = DataSet.props['filename']
                ff = filename.split('.')
                ff.insert(-1, str(i))
                filename = '.'.join(ff)
                truncated_weight = load_truncated_weight_for_dset(filename)
                truncated_weights.append(truncated_weight)
        else:
            filename = DataSet.props['filename']
            truncated_weight = load_truncated_weight_for_dset(filename)
            truncated_weights.append(truncated_weight)
        truncated_weights = numpy.array(truncated_weights)
        return truncated_weights

    eigen_measure_obs = pyalps.loadEigenstateMeasurements(
        result_files, what=['Energy'])
    for i in eigen_measure_obs:
        DataSet = i[0]
        truncated_weights = load_truncated_weight_for_dset_general_level(
            DataSet)
        i[0].y = truncated_weights
        i[0].props['observable'] = 'Truncated_Weight'

    ## 需要各组参数计算，都拥有相同数目的能级,依赖alps从低能级到高能级排
    truncated_weights = []
    num_levels = len(eigen_measure_obs[0][0].y)
    for i in range(num_levels):
        eigen_measure_obs_i = deepcopy(eigen_measure_obs)
        for j in eigen_measure_obs_i:
            j[0].y = np.array([j[0].y[i]])
        paras_vs_observables_i = pyalps.collectXY(
            eigen_measure_obs_i, x=propstring, y='Truncated_Weight')
        paras = paras_vs_observables_i[0].x
        observables_i = paras_vs_observables_i[0].y
        truncated_weights.append(observables_i)
    if num_levels == 1:
        truncated_weights = truncated_weights[0]
    truncated_weights = numpy.array(truncated_weights)
    return (paras, truncated_weights)


#(maxstates, truncation_error) = get_truncated_weight('MAXSTATES')
#print(maxstates)
#print(truncation_error)
